<template>
    <div class="white-box">
        <div class="flex items-center">
            <el-button
                v-hasPermi="['enttp:sms:add']"
                class="mr-10 table-mb"
                type="primary"
                @click="onClickAdd"
                >添加消息</el-button
            >
            <div
                v-hasPermi="['enttp:welink:message']"
                class="input-tips !mb-24"
            >
                短信条数<code>{{ state.smsInfo.numberUsedItems }}</code
                >/<code>{{ state.smsInfo.messagesTotal }}</code
                >，剩余<code>{{ state.smsInfo.remainingMessages }}</code
                >。
            </div>
        </div>

        <div class="task-one">
            <div class="task-one__item">
                <span class="task-one__label">消息标题：</span>
                <el-input
                    placeholder="请输入消息标题"
                    v-model="state.title"
                    @keyup.enter.native="handleSearch"
                    clearable
                >
                </el-input>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">消息类型：</span>
                <el-select
                    v-model="state.type"
                    placeholder="请选择类型"
                    clearable
                    multiple
                    collapse-tags
                >
                    <el-option
                        v-for="item in state.messageTypeList"
                        :key="item.memberKey"
                        :label="item.memberName"
                        :value="item.memberKey"
                    />
                </el-select>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">消息来源：</span>
                <el-select
                    v-model="state.source"
                    placeholder="请选择消息来源"
                    clearable
                >
                    <el-option
                        v-for="item in state.sourceList"
                        :key="item.memberKey"
                        :label="item.memberName"
                        :value="item.memberKey"
                    />
                </el-select>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">消息状态：</span>
                <el-select
                    v-model="state.state"
                    placeholder="请选择消息状态"
                    clearable
                >
                    <el-option
                        v-for="item in state.stateList"
                        :key="item.memberKey"
                        :label="item.memberName"
                        :value="item.memberKey"
                    />
                </el-select>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">启停状态：</span>
                <el-select
                    v-model="state.status"
                    placeholder="请选择状态"
                    clearable
                >
                    <el-option
                        v-for="item in state.statusList"
                        :key="item.memberKey"
                        :label="item.memberName"
                        :value="item.memberKey"
                    />
                </el-select>
            </div>
            <div class="task-one__btn clearfix">
                <el-button
                    type="primary"
                    :loading="loading"
                    icon="Search"
                    @click="handleSearch"
                    >搜索</el-button
                >
            </div>
        </div>

        <div>
            <el-button
                class="table-mb"
                v-hasPermi="['enttp:sms:del']"
                @click="onClickDel()"
                >批量删除消息</el-button
            >
        </div>

        <el-table
            class="table-mb"
            v-loading="loading"
            :data="arr_data"
            row-key="sid"
            :header-cell-style="{
                background: '#F5F7FA',
                textAlign: 'center',
            }"
            :cell-style="
                ({ column }) => {
                    return {
                        textAlign:
                            column.className === 'operation-nav'
                                ? 'left'
                                : 'center',
                        paddingLeft:
                            column.className === 'operation-nav' ? '25px' : '0',
                    };
                }
            "
            border
            element-loading-background="rgba(255, 255, 255, 0.6)"
            @selection-change="selectionChange"
            @sort-change="sortChange"
        >
            <el-table-column
                v-hasPermi="['enttp:sms:del']"
                type="selection"
                width="55"
            />
            <el-table-column
                prop="title"
                label="消息标题"
                min-width="250"
                fixed="left"
            ></el-table-column>
            <el-table-column prop="message" label="消息内容" min-width="200">
                <template #default="{ row }">
                    <el-button
                        v-hasPermi="['enttp:sms:query']"
                        type="primary"
                        link
                        @click="onClickMessageContent(row.sid)"
                    >
                        消息内容
                    </el-button>
                </template>
            </el-table-column>
            <el-table-column
                prop="type"
                label="类型"
                min-width="160"
                sortable="custom"
            >
                <template #default="{ row }">
                    {{
                        dictStore.getDictMemberName(
                            "enttp_message_reciever_type",
                            row.type
                        )
                    }}
                </template>
            </el-table-column>
            <el-table-column label="消息状态" min-width="160" sortable="custom">
                <template #default="{ row }">
                    {{
                        dictStore.getDictMemberName("message_state", row.state)
                    }}
                </template>
            </el-table-column>
            <el-table-column
                prop="status"
                label="状态"
                min-width="100"
                sortable="custom"
            >
                <template #default="{ row }">
                    {{ dictStore.getDictMemberName("data_status", row.status) }}
                </template>
            </el-table-column>
            <el-table-column
                prop="pushDatetime"
                label="推送时间"
                min-width="220"
                sortable="custom"
            ></el-table-column>
            <el-table-column
                label="操作"
                width="200"
                class-name="operation-nav"
                fixed="right"
            >
                <template #default="{ row }">
                    <MoreBtn
                        :buttons="[
                            // {
                            //     props: {
                            //         onClick: () => onClickDetails(row),
                            //     },
                            //     text: '详情',
                            // },
                            {
                                props: {
                                    onClick: () => release(row),
                                    'v-hasPermi': ['enttp:sms:publish'],
                                },
                                text: '发布',
                                isRender: row.state === 0 && row.status === 0,
                            },
                            {
                                props: {
                                    onClick: () => changeStatus(row.sid),
                                    'v-hasPermi': ['enttp:sms:update'],
                                },
                                text: ['停用', '启用'][row.status],
                            },
                            {
                                props: {
                                    onClick: () => onClickEdit(row.sid),
                                    'v-hasPermi': ['enttp:sms:edit'],
                                },
                                text: '修改',
                                isRender: row.state === 0,
                            },
                            {
                                props: {
                                    onClick: () => onClickDel(row.sid),
                                    'v-hasPermi': ['enttp:sms:del'],
                                },
                                text: '删除',
                            },
                        ]"
                    />
                </template>
            </el-table-column>
        </el-table>

        <el-pagination
            background
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :page-sizes="pageSizeNum"
            :total="totalNums"
            layout="slot, sizes, prev, pager, next, jumper"
        >
            <span class="color-#606266"
                >共&nbsp;{{
                    totalNums >= 100 * pageSize
                        ? `${100 * pageSize}+`
                        : totalNums
                }}&nbsp;条</span
            >
        </el-pagination>
    </div>

    <el-drawer v-model="state.showDetail" title="消息详情" size="540">
        <template v-if="detail">
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">消息标题</el-col>
                <el-col :span="18">{{ detail.title }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">消息内容</el-col>
                <el-col :span="18">{{ detail.message }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">消息类型</el-col>
                <el-col :span="18">{{
                    dictStore.getDictMemberName(
                        "enttp_message_reciever_type",
                        detail.type
                    )
                }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">消息状态</el-col>
                <el-col :span="18">{{
                    dictStore.getDictMemberName("message_state", detail.state)
                }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">推送时间</el-col>
                <el-col :span="18">{{ detail.pushDatetime }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">备注</el-col>
                <el-col :span="18">{{ detail.note }}</el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="6" align="end" class="mb-20">状态</el-col>
                <el-col :span="18">{{
                    dictStore.getDictMemberName("data_status", detail.status)
                }}</el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="6" align="end" class="mb-20">创建时间</el-col>
                <el-col :span="18">{{ detail.created }}</el-col>
            </el-row>
        </template>
    </el-drawer>

    <el-dialog v-model="state.showMessageContent" title="消息内容" width="1000">
        <div v-html="state.messageContent"></div>
    </el-dialog>
</template>

<script setup>
import { inject, reactive, onMounted, onActivated, toRefs } from "vue";
import { useRouter } from "vue-router";
import OneLoad from "@mixins/one-load";
import MoreBtn from "@/components/MoreBtn.vue";
import { ElMessageBox } from "element-plus";
import {
    getSMSs,
    delSMSs,
    changeSMSStatus,
    releaseSMS,
    getSMSDetail,
} from "@/apis/message.js";
import { getEnttpSMSInfo } from "@/apis/order/config.js";
import { useUserStore } from "@stores/user.js";
import { useDictStore } from "@stores/dict.js";

const dictStore = useDictStore();
dictStore
    .getDictMembers("message_state")
    .then((res) => (state.stateList = res));
dictStore.getDictMembers("data_status").then((res) => (state.statusList = res));
dictStore.getDictMembers("enttp_message_reciever_type").then(
    (res) =>
        (state.messageTypeList = res.filter(({ memberKey }) => {
            // 隐藏【商家邀请员工】选项，当角色为不是企业管理员时，隐藏【企业拥有者】
            if ([2, 5].includes(memberKey)) {
                return (
                    memberKey === 2 &&
                    (userStore.roleKeySet.includes("ent_owner") ||
                        userStore.roleKeySet.includes("ent_admin"))
                );
            } else {
                return true;
            }
        }))
);
dictStore
    .getDictMembers("message_channel_type")
    .then((res) => (state.sendTypeList = res));
dictStore
    .getDictMembers("message_source_type")
    .then((res) => (state.sourceList = res));

const router = useRouter();
const $message = inject("$message");

const userStore = useUserStore();

const state = reactive({
    statusList: [],
    stateList: [],
    messageTypeList: [],
    sendTypeList: [],
    sourceList: [],
    ascended: false,
    sortFieldName: null,
    title: null,
    type: null,
    source: null,
    status: null,
    sidList: [],
    showDetail: false,
    detail: null,
    smsInfo: {
        messagesTotal: 0,
        numberUsedItems: 0,
        remainingMessages: 0,
    },
    showMessageContent: false,
    messageContent: null,
});
const { detail } = toRefs(state);

onMounted(() => {
    state.type = [1, 3, 4];
    if (
        userStore.roleKeySet.includes("ent_owner") ||
        userStore.roleKeySet.includes("ent_admin")
    ) {
        state.type.push(2);
    }
});

onActivated(() => {
    pubParams(getList);
    getSMSInfo();
});

const getSMSInfo = async () => {
    const res = await getEnttpSMSInfo();
    if (res.data.code == 200) {
        state.smsInfo = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

/**
 * minxin列表加载
 */
const {
    loading,
    arr_data,
    pubRefreshParams,
    pubParams,
    page,
    pageSize,
    getdata,
    pageSizeNum,
    totalNums,
    openPaging,
} = OneLoad();

openPaging(getList);

function getList() {
    getdata(
        getSMSs({
            current: page.value,
            size: pageSize.value,
            ascended: state.ascended,
            sortFieldName: state.sortFieldName,
            title: state.title,
            type: state.type.toString(),
            source: state.source,
            status: state.status,
            state: state.state,
        })
    );
}

// 搜索
const handleSearch = () => {
    pubRefreshParams(getList);
};

// 跳转到新增页
const onClickAdd = () => {
    router.push({
        name: "SMSMessageAdd",
    });
};

// 排序
const sortChange = (e) => {
    const { property, order } = e.column;
    state.ascended = order === "ascending";
    state.sortFieldName = order ? property : null;
    pubRefreshParams(getList);
};

// 发布消息
const release = async (sid) => {
    const res = await releaseSMS({ sid });
    if (res.data.code == 200) {
        $message({ message: "发布成功", type: "success" });
        pubParams(getList);
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const onClickDetails = (row) => {
    state.showDetail = true;
    state.detail = row;
};

const onClickMessageContent = async (sid) => {
    state.showMessageContent = true;
    state.messageContent = null;
    const res = await getSMSDetail({ sid });
    if (res.data.code == 200) {
        state.messageContent = res.data.data.message;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 点击修改按钮
const onClickEdit = (sid) => {
    sid &&
        router.push({
            name: "SMSMessageEdit",
            query: {
                sid,
            },
        });
};

// 切换状态
const changeStatus = async (sid) => {
    const res = await changeSMSStatus({ sid });
    if (res.data.code == 200) {
        $message({ message: "操作成功", type: "success" });
        pubParams(getList);
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 选中项改变
const selectionChange = (e) => {
    state.sidList = e.map((item) => item.sid);
};

// 删除
const onClickDel = async (sid) => {
    if (sid) {
        state.sidList = [sid];
    }
    if (!state.sidList.length) {
        return $message({ message: "请先勾选要删除的数据", type: "warning" });
    }
    await ElMessageBox.confirm("确定删除消息吗？");
    const res = await delSMSs({ sidList: state.sidList });
    if (res.data.code == 200) {
        $message({ message: "删除成功", type: "success" });
        pubParams(getList);
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};
</script>

<style lang="less" scoped></style>
